from datetime import datetime, timedelta

from odoo import fields, models, api


class MrpWorkStationOrder(models.Model):
    _name = 's.mrp.work.station.order'
    _description = 'Station Order'

    production_id = fields.Many2one('mrp.production', string='Production')
    station_id = fields.Many2one('work.station', string='Station', copy=False)
    workorder_ids = fields.One2many('mrp.workorder', 's_station_order', string='Work Order')
    done_date = fields.Datetime('Done Date', copy=False)
    qty = fields.Integer('Qty')
    qty_set = fields.Integer('Qty(SET)')
    qty_pnl = fields.Integer('Qty(PNL)')

    state = fields.Selection([
        ('progress', 'Progress'),
        ('done', 'Done'),
        ('cancel', 'Cancel')
    ], string='Status', readonly=True, copy=False, default='progress')
    done = fields.Boolean('Done', default=False, copy=False)
    step = fields.Integer('Step')

    def constrains_done(self):
        unlink = self.env['s.mrp.work.station.order']
        for rec in self:
            if rec.done:
                continue
            if not rec.workorder_ids:
                unlink |= rec
            elif all([workorder.state == 'done' for workorder in rec.workorder_ids]):
                done_date = rec.workorder_ids.sorted(lambda x: x.step)[-1].date_finished
                rec.update({
                    'done': True,
                    'done_date': done_date
                })
                for task in rec.task_ids.filtered(lambda x: x.state == 'progress'):
                    now_date = fields.Date.to_date(done_date)
                    # 以泰国时间八点半为分界
                    if done_date.hour < 1 or (done_date.hour == 1 and done_date.minute < 30):
                        now_date = now_date - timedelta(days=1)

                    if now_date > task.planned_completion_date:
                        state = 'fail'
                    else:
                        state = 'done'
                    task.write({
                        'state': state,
                        'actual_completion_datetime': done_date,
                        'actual_completion_date': now_date
                    })

        unlink.sudo().unlink()
